<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\api\controller\Index;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function import(){
        $data = array();
        $string = '';
        $d1 = explode(PHP_EOL,$string);
        foreach($d1 as $val){
            $line = explode('	',$val);
            $f_id = Db::name('floor') ->where('u_id',$line[0])->where('name',$line[1])->value('id');//房号
            $b_id = 1;//栋
            $u_id = $line[0];//单元
            $number = 0;//居住人数
            $user_info = array();
            $time = date('Y-m-d');
            if(isset($line[2]) && isset($line[3]) && isset($line[4]) && isset($line[5])){
                if($line[2]!='' && $line[3]!='' && $line[4]!='' && $line[5]!='')
                $user_info[] = array('name'=>$line[2],'sex'=>$line[3],'card_no'=>$line[4],'phone'=>$line[5],'time'=>$time);
            }
            if(isset($line[6]) && isset($line[7]) && isset($line[8]) && isset($line[9])){
                if($line[6]!='' && $line[7]!='' && $line[8]!='' && $line[9]!='')
                $user_info[] = array('name'=>$line[6],'sex'=>$line[7],'card_no'=>$line[8],'phone'=>$line[9],'time'=>$time);
            }
            if(isset($line[10]) && isset($line[11]) && isset($line[12]) && isset($line[13])){
                if($line[10]!='' && $line[11]!='' && $line[12]!='' && $line[13]!='')
                $user_info[] = array('name'=>$line[10],'sex'=>$line[11],'card_no'=>$line[12],'phone'=>$line[13],'time'=>$time);
            }
            $number = count($user_info);
            echo($u_id.','.$b_id.','.$f_id.','.$number.','.$line[14]);
            dump($user_info);
            self::save_data($u_id,$b_id,$f_id,$number,'',$line[14],$user_info);
        }
        //
    }

    private function save_data($u_id,$b_id,$f_id,$number,$detail,$type,$user_info){
        //判断是否已经申报
        //获取今天的时间戳
        $start_time = strtotime(date('Y-m-d',time()));
        $end_time =time();
        $card_nos = [];
        $today_number = 0;//登记人数
        foreach ($user_info as $key=>$item){

            $user_info[$key]['is_check'] =0;
            if(!isset($item['name']) || !$item['name']){
                $this->error('请填写姓名','',201);
            }
            if(!isset($item['sex']) || !$item['sex']){
                $this->error('请选择性别','',201);
            }
            if(!isset($item['card_no']) || !$item['card_no']){
                $this->error('请填写身份证号','',201);
            }
            if(!isset($item['phone']) || !$item['phone']){
                $this->error('请填写联系电话','',201);
            }
            if(!isset($item['time']) || !$item['time']){
                $this->error('请选择最后一次核酸时间','',201);
            }
            //判断身份证号码
            //$model = new \app\api\controller\Index;
            //$is_true = $model->isCreditNo($item['card_no']);
            //if(!$is_true){
                //$this->error($item['name'].'身份证号码错误，请重新填写','',201);
            //}
            //判断重复提交
            if(in_array($item['card_no'],$card_nos)){
                $this->error($item['name'].'已存在，请勿重复登记','',201);
            }
            $card_nos[] = $item['card_no'];
            //判断今天是否登记
            $is_check = Db::name('data_user') ->where('card_no',$item['card_no'])->whereTime('createtime','between',[$start_time,$end_time])->value('id');
            if($is_check){
                $user_info[$key]['is_check'] =1;//标记为已登记
            }else{
                $today_number ++;//增加登记人数
            }
        }

        Db::startTrans();
        $result = $res1 =true;
        try {
            //如果居住人数大于之前登记人数  则更新登记人数
            $floor_number = Db::name('floor')->where('id',$f_id)->value('people');
            if(floatval($number) > floatval($floor_number)){
                $res = Db::name('floor')->where('id',$f_id)->update(['people'=>$number]);
                if($res === false){
                    $result = false;
                }
            }
            $data = [
                'u_id' =>$u_id,
                'b_id' =>$b_id,
                'f_id' =>$f_id,
                'number' =>$number,
                'today_number' =>count($user_info),
                'type' =>$type,
                'detail' =>$detail,
                'createtime' =>time(),
            ];
            //判断该房号今天是否已经申报
            $is_check = Db::name('data_table')->where('f_id',$f_id) ->whereTime('createtime','between',[$start_time,$end_time])->value('id');
            if($is_check){
                $data_id = $is_check;
                //修改今天登记人数
                $data['today_number'] += $today_number;
                $res1 = Db::name('data_table') ->where('id',$data_id) ->update($data);
                if($res1 === false){
                    $result = false;
                }
            }
            else{
                $data_id = Db::name('data_table') ->insertGetId($data);
            }
            $user_data = [];
            foreach ($user_info as $item){
                $item['d_id'] = $data_id;
                $item['time'] = strtotime($item['time']);
                $item['createtime'] = time();
                if($item['is_check'] == 0){
                    unset($item['is_check']);
                    $user_data[] = $item;
                }
            }
            if($user_data){
                $re2 = Db::name('data_user') ->insertAll($user_data);
                if($re2  === false){
                    $result = false;
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(),'',201);
        }
        if ($result === false) {
            $this->error('填报失败','',201);
        }
        //获取该房号当日的登记记录
        $list = Db::name('data_user')->where('d_id',$data_id)->whereTime('createtime','between',[$start_time,$end_time])->select();
        foreach ($list as &$item){
            $item['time'] = date('m-d',$item['time']);
        }
        //$this->success('成功',$list,200);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
